<?php

require './config.php';

use Thenbsp\Wechat\OAuth\Client;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

$client = new Client(APPID, APPSECRET);
$client->setScope('snsapi_userinfo');
$client->setRedirectUri(URL.'/authorize');

/**
 * 当前请求对象
 */
$request = Request::createFromGlobals();

/**
 * 获取授权地址
 */
if (!$request->query->has('authorization_code')) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_OK,
        'data' => $client->getAuthorizeUrl()
    ]);
    $response->send();
}

$_authorizationCode = $request->query->get('authorization_code');

/**
 * 根据 code 换取微信 access_token
 */
try {
    $accessToken = $client->getAccessToken($_authorizationCode);
} catch (\Exception $e) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR,
        'data' => $e->getMessage()
    ]);
    $response->send();
}

/**
 * 根据 openid 获取用户信息
 */
$token = getAccessTokenByOpenid($accessToken['openid']);

if (!$token) {
    $response = new JsonResponse([
        'code' => JsonResponse::HTTP_INTERNAL_SERVER_ERROR,
        'data' => '您当前微信帐号未绑定帐号，请先通过帐号密码登录！'
    ]);
    $response->send();
}

$response = new JsonResponse([
    'code' => JsonResponse::HTTP_OK,
    'data' => [
        'access_token'  => $token['token'],
        'expire_in'     => EXPIRES_SECONDS
    ]
]);
$response->send();
